import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import ForgetPassword from '../views/ForgetPassword.vue';
import UserInfo from '../views/UserInfo.vue';
import UpdateUserInfo from '../views/UpdateUserInfo.vue';
import ArticleSearch from '../views/ArticleSearch.vue';
import WriteArticle from '../views/WriteArticle.vue';
import ViewArticle from '../views/ViewArticle.vue';
import PersonalPage from '../views/PersonalPage.vue';
import FollowingPage from '../views/FollowingPage.vue';
import FollowerPage from '../views/FollowerPage.vue';
import CategoriesPage from '../views/Categories.vue';
import TagsPage from '../views/Tags.vue';
import ArchivesPage from '../views/Archives.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/forget-password',
    name: 'ForgetPassword',
    component: ForgetPassword
  },
  {
    path: '/user/info',
    name: 'UserInfo',
    component: UserInfo,
    meta: { requiresAuth: true }
  },
  {
    path: '/user/update',
    name: 'UpdateUserInfo',
    component: UpdateUserInfo,
    meta: { requiresAuth: true }
  },
  {
    path: '/article/search',
    name: 'ArticleSearch',
    component: ArticleSearch
  },
  {
    path: '/writeArticle',
    name: 'WriteArticle',
    component: WriteArticle
  },
  {
    path: '/writeArticle/:id',
    name: 'EditArticle',
    component: WriteArticle
  },
  {
    path: '/viewArticle/:id',
    name: 'ViewArticle',
    component: ViewArticle
  },
  {
    path: '/user/:userId',
    name: 'PersonalPage',
    component: PersonalPage
  },
  {
    path: '/user/:userId/following',
    name: 'FollowingPage',
    component: FollowingPage
  },
  {
    path: '/user/:userId/followers',
    name: 'FollowerPage',
    component: FollowerPage
  },
  {
    path: '/categories',
    name: 'CategoriesPage',
    component: CategoriesPage
  },
  {
    path: '/tags',
    name: 'TagsPage',
    component: TagsPage
  },
  {
    path: '/archives',
    name: 'ArchivesPage',
    component: ArchivesPage
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录
    if (!localStorage.getItem('token')) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;